﻿using System;
using System.Linq;
using Company.Merchandising.BusinessLayer.DataEntities;
using Company.Merchandising.BusinessLayer.DataTransferObjects;
using Company.Merchandising.DataAccessLayer.DataAccessCommon;
using Company.Merchandising.ServiceLayer.EntityManagement.Constants;
using CompanyEntity = Company.Merchandising.BusinessLayer.DataEntities.Company;

namespace Company.Merchandising.ServiceLayer.EntityManagement
{
	public class CompanyManager : BaseManager
	{
		public CompanyManager(MerchModelEntities modelEntities) : base(modelEntities) { }

		public void DeleteCompany(DTOCompany dtoCompany)
		{
			var company = new DACCompany(_modelEntities).GetCompanyById(dtoCompany.Id);
			if (company == null)
			{
				throw new InvalidOperationException(string.Format(ExceptionMessages.CompanyDoesNotExistAnyMore, dtoCompany.Id));
			}

			_modelEntities.DeleteObject(company);
			_modelEntities.SaveChanges();
		}

		public void UpdateCompany(DTOCompany dtoCompany)
		{
			DACCompany dacCompany = new DACCompany(_modelEntities);
			var count = dacCompany.GetCompaniesByNameOtherThan(dtoCompany.Name, dtoCompany.Id).Count();
			if (count > 0)
			{
				throw new InvalidOperationException(string.Format(ExceptionMessages.CompanyAlreadyExist, dtoCompany.Name));
			}

			var company = dacCompany.GetCompanyById(dtoCompany.Id);
			if (company == null)
			{
				throw new InvalidOperationException(string.Format(ExceptionMessages.CompanyDoesNotExistAnyMore, dtoCompany.Id));
			}

			company.Name = dtoCompany.Name;
			company.FullName = dtoCompany.FullName;
			company.IsDefault = dtoCompany.IsDefault;

			if (company.IsDefault)
			{
				var defaultCompanies = dacCompany.GetDefaultCompaniesOtherThan(company.Name);
				foreach (var defaultCompany in defaultCompanies)
				{
					defaultCompany.IsDefault = false;
				}
			}

			_modelEntities.SaveChanges();
		}

		public void AddCompany(DTOCompany dtoCompany)
		{
			DACCompany dacCompany = new DACCompany(_modelEntities);
			var count = dacCompany.GetCompaniesByName(dtoCompany.Name).Count();
			if (count > 0)
			{
				throw new InvalidOperationException(string.Format(ExceptionMessages.CompanyAlreadyExist, dtoCompany.Name));
			}

			CompanyEntity company = new CompanyEntity();
			company.Name = dtoCompany.Name;
			company.FullName = dtoCompany.FullName;
			company.IsDefault = dtoCompany.IsDefault;

			if (company.IsDefault)
			{
				var defaultCompanies = dacCompany.GetDefaultCompaniesOtherThan(company.Name);
				foreach (var defaultCompany in defaultCompanies)
				{
					defaultCompany.IsDefault = false;
				}
			}

			_modelEntities.AddObject(company.GetType().Name, company);
			_modelEntities.SaveChanges();
		}
	}
}
